package com.example.kt_wear_app.presentation.utils

import com.google.android.gms.common.internal.Objects
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken
import org.eclipse.paho.client.mqttv3.MqttCallback
import org.eclipse.paho.client.mqttv3.MqttClient
import org.eclipse.paho.client.mqttv3.MqttConnectOptions
import org.eclipse.paho.client.mqttv3.MqttException
import org.eclipse.paho.client.mqttv3.MqttMessage
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence


object MqttUtils {
    private lateinit var mqttClient: MqttClient
    private lateinit var connOpts: MqttConnectOptions
    private lateinit var BROKER: String
    private lateinit var CLIENT_ID: String
    private val persistence = MemoryPersistence()

    // 初始化 MQTT 客户端
    fun initClient(config: Any? = null) {
        // 当传入配置对象时更新属性
        config?.let { 
            BROKER = (it as Map<String, String>)["server"].toString()
            CLIENT_ID = (it as Map<String, String>)["clientId"].toString()
        }
        println("wx://$BROKER:1883/mqtt")
        // 确保使用最新属性值初始化客户端
        mqttClient = MqttClient("wx://$BROKER:1883/mqtt", CLIENT_ID, persistence)
        connOpts = MqttConnectOptions().apply {
            isCleanSession = true
            userName = "sf_app"
            password = "giftwl12".toCharArray()
            keepAliveInterval = 60
            // 可以在此添加更多连接配置
        }
        
        // 保持原有回调设置不变...
        mqttClient.setCallback(object : MqttCallback {
            override fun connectionLost(cause: Throwable?) {
                println("Connection lost: ${cause?.message}")
            }
            override fun messageArrived(topic: String?, message: MqttMessage?) {
                println("Received message: ${message?.toString()} on topic: $topic")
            }
            override fun deliveryComplete(token: IMqttDeliveryToken?) {
                println("Message delivered")
            }
        })
        mqttClient.connect(connOpts)
    }


    // 连接到 MQTT 服务器
    private fun connect() {
        try {
            initClient()
            println("Connecting to broker: $BROKER")
            mqttClient.connect(connOpts)
            println("Connected")
        } catch (e: MqttException) {
            println("MqttException while connecting: ${e.message}")
        }
    }

    // 订阅主题
    fun subscribe(topic: String) {
        try {
            if (mqttClient.isConnected) {
                mqttClient.subscribe(topic)
                println("Subscribed to topic: $topic")
            } else {
                println("Not connected. Cannot subscribe.")
            }
        } catch (e: MqttException) {
            println("MqttException while subscribing: ${e.message}")
        }
    }

    // 发布消息
    fun publish(topic: String, message: String) {
        try {
            if (mqttClient.isConnected) {
                val mqttMessage = MqttMessage(message.toByteArray())
                mqttClient.publish(topic, mqttMessage)
                println("Message published: $message")
            } else {
                println("Not connected. Cannot publish.")
            }
        } catch (e: MqttException) {
            println("MqttException while publishing: ${e.message}")
        }
    }

    // 断开与 MQTT 服务器的连接
    fun disconnect() {
        try {
            if (mqttClient.isConnected) {
                mqttClient.disconnect()
                println("Disconnected")
            } else {
                println("Already disconnected.")
            }
        } catch (e: MqttException) {
            println("MqttException while disconnecting: ${e.message}")
        }
    }


}